<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>食品营养知识图谱 - 营养健康系统</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js"></script>
    <script src="../js/api-service.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: #047857;
            --secondary-color: #059669;
            --accent-color: #10b981;
            --food-color: #f59e0b;
            --nutrient-color: #3b82f6;
            --benefit-color: #10b981;
            --background-light: #f9fafb;
            --background-dark: #f3f4f6;
            --text-primary: #1f2937;
            --text-secondary: #4b5563;
            --text-light: #6b7280;
        }
        
        body {
            font-family: 'Nunito', sans-serif;
        }
        
        .gradient-bg {
            background-color: #f9fafb;
            background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%2310b981' fill-opacity='0.03'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
        }
        
        .nav-link {
            position: relative;
            color: var(--text-secondary);
            font-weight: 500;
            padding: 0.5rem 1rem;
            transition: all 0.3s;
        }
        
        .nav-link:hover {
            color: var(--primary-color);
        }
        
        .nav-link.active {
            color: var(--primary-color);
            font-weight: 600;
        }
        
        .nav-link.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 2px;
            background-color: var(--primary-color);
        }
        
        .sidebar-item {
            transition: all 0.3s;
            cursor: pointer;
            border-left: 3px solid transparent;
        }
        
        .sidebar-item:hover {
            background-color: rgba(237, 242, 247, 0.8);
            transform: translateX(5px);
            border-left: 3px solid var(--primary-color);
        }
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 10;
        }
        .spinner {
            width: 60px;
            height: 60px;
            border: 5px solid #e2e8f0;
            border-top: 5px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        .loading-text {
            margin-top: 15px;
            font-size: 14px;
            color: var(--primary-color);
            font-weight: 600;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        .chart-container {
            position: relative;
            height: 650px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }
        .view-toggle {
            position: absolute;
            top: 10px;
            right: 10px;
            z-index: 5;
        }
        .search-history-item {
            transition: all 0.2s;
            padding: 0.5rem;
            border-radius: 0.25rem;
            display: flex;
            align-items: center;
        }
        
        .search-history-item:hover {
            background-color: rgba(237, 242, 247, 0.8);
        }
        
        .node-tooltip {
            position: absolute;
            background-color: white;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            padding: 8px 12px;
            font-size: 12px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            z-index: 100;
            max-width: 200px;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.2s;
        }
        
        .card-shadow {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        
        .card-shadow:hover {
            box-shadow: 0 10px 15px rgba(0, 0, 0, 0.05), 0 4px 6px rgba(0, 0, 0, 0.05);
        }
        
        .logo-text {
            color: white;
            font-weight: bold;
        }
        
        .tag {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
        }
        
        .tag-food {
            background-color: rgba(237, 137, 54, 0.2);
            color: #c05621;
        }
        
        .tag-nutrient {
            background-color: rgba(66, 153, 225, 0.2);
            color: #2b6cb0;
        }
        
        .tag-benefit {
            background-color: rgba(72, 187, 120, 0.2);
            color: #2f855a;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
<!-- 顶部导航栏 -->
<nav class="bg-green-600 text-white shadow-lg">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center">
            <svg class="h-10 w-10 mr-3" viewBox="0 0 100 100">
                <circle cx="50" cy="50" r="45" fill="#4CAF50" />
                <text x="50" y="55" font-size="20" text-anchor="middle" fill="white">营养</text>
                <path d="M30,70 Q50,90 70,70" stroke="white" stroke-width="3" fill="none" />
            </svg>
            <h1 class="text-xl font-bold logo-text">营养健康系统</h1>
        </div>
        <div class="hidden md:flex space-x-6">
            <a href="../index.html" class="hover:text-green-200">
                <i class="fas fa-home mr-1"></i>首页
            </a>
            <a href="food-analysis.html" class="hover:text-green-200">
                <i class="fas fa-apple-alt mr-1"></i>食品分析
            </a>
            <a href="health-profile.html" class="hover:text-green-200">
                <i class="fas fa-heartbeat mr-1"></i>健康档案
            </a>
            <a href="diet-records.html" class="hover:text-green-200">
                <i class="fas fa-utensils mr-1"></i>饮食记录
            </a>
            <a href="nutrition-charts.html" class="hover:text-green-200">
                <i class="fas fa-chart-pie mr-1"></i>营养图表
            </a>
            <a href="knowledge-graph.html" class="hover:text-green-200 border-b-2 border-white">
                <i class="fas fa-project-diagram mr-1"></i>知识图谱
            </a>
        </div>
            <div class="flex items-center space-x-4 nav-user-section">
                <!-- 这里的内容将由auth.js动态更新 -->
                <a href="login.html" class="hover:text-green-200">登录</a>
                <a href="register.html" class="bg-white text-green-600 px-4 py-2 rounded-lg hover:bg-green-100">注册</a>
            </div>
    </div>
</nav>

<!-- 页面标题 -->
<div class="bg-green-500 text-white py-8">
    <div class="container mx-auto px-4">
        <h2 class="text-3xl font-bold">食品营养知识图谱</h2>
        <p class="mt-2">探索食品、营养素与健康功效之间的关系</p>
    </div>
</div>

<!-- 主体内容区 -->
<div class="container mx-auto px-4 py-8">
    <div class="flex flex-wrap -mx-4">
        <!-- 左侧侧边栏 -->
        <div class="w-full md:w-1/5 px-4 mb-6">
            <div class="bg-white rounded-lg shadow-md p-4">
                <h3 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fas fa-bolt text-yellow-500 mr-2"></i>快捷查询
                </h3>
                <div class="mb-4">
                    <div class="relative">
                        <input type="text" id="searchInput" placeholder="搜索食品..."
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500">
                        <button onclick="search()" class="absolute right-2 top-2 text-green-600 hover:text-green-800">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                    <div id="searchResults" class="mt-2 max-h-40 overflow-y-auto hidden">
                        <!-- 搜索结果将通过JS动态添加 -->
                    </div>
                </div>
                <div class="space-y-2" id="quickSearchList">
                    <!-- 快捷查询列表将通过API动态加载 -->
                </div>
                
                <h3 class="text-lg font-semibold mt-6 mb-4 flex items-center">
                    <i class="fas fa-fire text-orange-500 mr-2"></i>热门搜索
                </h3>
                <div class="flex flex-wrap gap-2" id="hotSearchTags">
                    <!-- 热门搜索标签将通过JS动态添加 -->
                </div>
                
                <h3 class="text-lg font-semibold mt-6 mb-4 flex items-center">
                    <i class="fas fa-history text-blue-500 mr-2"></i>搜索历史
                </h3>
                <div class="space-y-2" id="searchHistory">
                    <!-- 搜索历史将通过JS动态添加 -->
                </div>
                <div class="mt-2 text-right" id="clearHistoryBtn">
                    <button class="text-xs text-gray-500 hover:text-red-500">
                        <i class="fas fa-trash-alt mr-1"></i>清除历史
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 中央主体区 -->
        <div class="w-full md:w-3/5 px-4 mb-6">
            <div class="bg-white rounded-lg shadow-md p-4">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-semibold flex items-center">
                        <i class="fas fa-project-diagram text-green-600 mr-2"></i>
                        <span id="graphTitle">食品营养知识图谱</span>
                    </h2>
                    <div class="flex space-x-2">
                        <button id="exportImageBtn" class="bg-green-100 hover:bg-green-200 text-green-700 px-3 py-1 rounded-md text-sm flex items-center transition duration-300">
                            <i class="fas fa-image mr-1"></i>导出图片
                        </button>
                        <button id="exportDataBtn" class="bg-green-100 hover:bg-green-200 text-green-700 px-3 py-1 rounded-md text-sm flex items-center transition duration-300">
                            <i class="fas fa-file-download mr-1"></i>导出数据
                        </button>
                    </div>
                </div>
                
                <div class="chart-container rounded-lg border border-gray-200 overflow-hidden">
                    <!-- 视图切换按钮 -->
                    <div class="view-toggle">
                        <button id="graphViewBtn" class="bg-green-600 text-white px-3 py-1 rounded-l-md text-sm shadow-sm">
                            <i class="fas fa-project-diagram mr-1"></i>图谱视图
                        </button>
                        <button id="listViewBtn" class="bg-gray-200 text-gray-700 px-3 py-1 rounded-r-md text-sm shadow-sm">
                            <i class="fas fa-list mr-1"></i>列表视图
                        </button>
                    </div>
                    
                    <!-- 图谱容器 -->
                    <div id="chart" style="height:650px;"></div>
                    
                    <!-- 列表视图容器 (默认隐藏) -->
                    <div id="listView" class="hidden p-4 h-full overflow-auto">
                        <!-- 列表视图内容将通过JS动态生成 -->
                    </div>
                    
                    <!-- 加载动画 -->
                    <div id="loadingOverlay" class="loading-overlay hidden">
                        <div class="spinner"></div>
                        <div class="loading-text mt-4">正在加载知识图谱...</div>
                    </div>
                    
                    <!-- 节点提示框 -->
                    <div id="nodeTooltip" class="node-tooltip"></div>
                </div>
                
                <!-- 统计信息 -->
                <div id="statsInfo" class="mt-4 p-4 bg-green-50 rounded-lg text-sm text-gray-700 shadow-sm">
                    <h3 class="text-md font-semibold mb-2 flex items-center">
                        <i class="fas fa-chart-bar text-green-500 mr-2"></i>图谱统计
                    </h3>
                    <div class="flex flex-wrap items-center">
                        <div class="flex items-center mr-6 bg-white px-3 py-2 rounded-full shadow-sm">
                            <div class="w-3 h-3 rounded-full bg-yellow-500 mr-2"></div>
                            <span>食品: <span id="foodCount" class="font-semibold text-yellow-600">0</span>个</span>
                        </div>
                        <div class="flex items-center mr-6 bg-white px-3 py-2 rounded-full shadow-sm">
                            <div class="w-3 h-3 rounded-full bg-blue-500 mr-2"></div>
                            <span>营养素: <span id="nutrientCount" class="font-semibold text-blue-600">0</span>种</span>
                        </div>
                        <div class="flex items-center bg-white px-3 py-2 rounded-full shadow-sm">
                            <div class="w-3 h-3 rounded-full bg-green-500 mr-2"></div>
                            <span>功效: <span id="benefitCount" class="font-semibold text-green-600">0</span>个</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 右侧数据图表 -->
        <div class="w-full md:w-1/5 px-4 mb-6">
            <div class="bg-white rounded-lg shadow-md p-4">
                <h3 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fas fa-chart-pie text-green-500 mr-2"></i>营养成分分布
                </h3>
                <div id="nutrientPieChart" style="height:220px;"></div>
                
                <h3 class="text-lg font-semibold mt-6 mb-4 flex items-center">
                    <i class="fas fa-info-circle text-green-500 mr-2"></i>详细信息
                </h3>
                <div id="detailInfo" class="text-sm text-gray-600 bg-gray-50 p-3 rounded-lg">
                    <p class="mb-2">选择图谱中的节点查看详细信息</p>
                    <div class="flex flex-wrap gap-2 mt-3">
                        <span class="tag tag-food">食品</span>
                        <span class="tag tag-nutrient">营养素</span>
                        <span class="tag tag-benefit">功效</span>
                    </div>
                </div>
                
                <div class="mt-6 p-3 bg-green-50 rounded-lg">
                    <h4 class="font-semibold text-green-700 mb-2 flex items-center">
                        <i class="fas fa-lightbulb text-yellow-500 mr-2"></i>小贴士
                    </h4>
                    <p class="text-sm text-gray-600">点击图谱中的节点可查看详细信息，滚轮缩放可放大或缩小图谱。</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 底部版权信息 -->
<footer class="bg-green-800 text-white py-10 mt-12">
    <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
            <div>
                <h3 class="text-lg font-semibold mb-4">关于我们</h3>
                <p class="text-green-200">营养健康系统致力于通过先进技术帮助用户了解食品营养成分，提供个性化健康建议。</p>
            </div>
            <div>
                <h3 class="text-lg font-semibold mb-4">快速链接</h3>
                <ul class="space-y-2 text-green-200">
                    <li><a href="../index.html" class="hover:text-white">首页</a></li>
                    <li><a href="food-analysis.html" class="hover:text-white">食品分析</a></li>
                    <li><a href="health-profile.html" class="hover:text-white">健康档案</a></li>
                    <li><a href="diet-records.html" class="hover:text-white">饮食记录</a></li>
                    <li><a href="nutrition-charts.html" class="hover:text-white">营养图表</a></li>
                    <li><a href="knowledge-graph.html" class="hover:text-white">知识图谱</a></li>
                </ul>
            </div>
            <div>
                <h3 class="text-lg font-semibold mb-4">联系我们</h3>
                <ul class="space-y-2 text-green-200">
                    <li>邮箱：2541147551@nutrition-health.com</li>
                    <li>电话：400-123-4567</li>
                    <li>地址：丰和南大道696号</li>
                </ul>
            </div>
            <div>
                <h3 class="text-lg font-semibold mb-4">关注我们</h3>
                <div class="flex space-x-4">
                    <a href="#" class="text-green-200 hover:text-white">
                        <svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M22.675 0h-21.35c-.732 0-1.325.593-1.325 1.325v21.351c0 .731.593 1.324 1.325 1.324h11.495v-9.294h-3.128v-3.622h3.128v-2.671c0-3.1 1.893-4.788 4.659-4.788 1.325 0 2.463.099 2.795.143v3.24l-1.918.001c-1.504 0-1.795.715-1.795 1.763v2.313h3.587l-.467 3.622h-3.12v9.293h6.116c.73 0 1.323-.593 1.323-1.325v-21.35c0-.732-.593-1.325-1.325-1.325z"/>
                        </svg>
                    </a>
                    <a href="#" class="text-green-200 hover:text-white">
                        <svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M23.953 4.57a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723 10.054 10.054 0 01-3.127 1.184 4.92 4.92 0 00-8.384 4.482C7.69 8.095 4.067 6.13 1.64 3.162a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.06a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.936 4.936 0 004.604 3.417 9.867 9.867 0 01-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 007.557 2.209c9.053 0 13.998-7.496 13.998-13.985 0-.21 0-.42-.015-.63A9.935 9.935 0 0024 4.59z"/>
                        </svg>
                    </a>
                    <a href="#" class="text-green-200 hover:text-white">
                        <svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M12 0C8.74 0 8.333.015 7.053.072 5.775.132 4.905.333 4.14.63c-.789.306-1.459.717-2.126 1.384S.935 3.35.63 4.14C.333 4.905.131 5.775.072 7.053.012 8.333 0 8.74 0 12s.015 3.667.072 4.947c.06 1.277.261 2.148.558 2.913.306.788.717 1.459 1.384 2.126.667.666 1.336 1.079 2.126 1.384.766.296 1.636.499 2.913.558C8.333 23.988 8.74 24 12 24s3.667-.015 4.947-.072c1.277-.06 2.148-.262 2.913-.558.788-.306 1.459-.718 2.126-1.384.666-.667 1.079-1.335 1.384-2.126.296-.765.499-1.636.558-2.913.06-1.28.072-1.687.072-4.947s-.015-3.667-.072-4.947c-.06-1.277-.262-2.149-.558-2.913-.306-.789-.718-1.459-1.384-2.126C21.319 1.347 20.651.935 19.86.63c-.765-.297-1.636-.499-2.913-.558C15.667.012 15.26 0 12 0zm0 2.16c3.203 0 3.585.016 4.85.071 1.17.055 1.805.249 2.227.415.562.217.96.477 1.382.896.419.42.679.819.896 1.381.164.422.36 1.057.413 2.227.057 1.266.07 1.646.07 4.85s-.015 3.585-.074 4.85c-.061 1.17-.256 1.805-.421 2.227-.224.562-.479.96-.899 1.382-.419.419-.824.679-1.38.896-.42.164-1.065.36-2.235.413-1.274.057-1.649.07-4.859.07-3.211 0-3.586-.015-4.859-.074-1.171-.061-1.816-.256-2.236-.421-.569-.224-.96-.479-1.379-.899-.421-.419-.69-.824-.9-1.38-.165-.42-.359-1.065-.42-2.235-.045-1.26-.061-1.649-.061-4.844 0-3.196.016-3.586.061-4.861.061-1.17.255-1.814.42-2.234.21-.57.479-.96.9-1.381.419-.419.81-.689 1.379-.898.42-.166 1.051-.361 2.221-.421 1.275-.045 1.65-.06 4.859-.06l.045.03zm0 3.678c-3.405 0-6.162 2.76-6.162 6.162 0 3.405 2.76 6.162 6.162 6.162 3.405 0 6.162-2.76 6.162-6.162 0-3.405-2.76-6.162-6.162-6.162zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm7.846-10.405c0 .795-.646 1.44-1.44 1.44-.795 0-1.44-.646-1.44-1.44 0-.794.646-1.439 1.44-1.439.793-.001 1.44.645 1.44 1.439z"/>
                        </svg>
                    </a>
                </div>
            </div>
        </div>
        <div class="border-t border-green-700 mt-8 pt-6 text-center text-green-300">
            <p>&copy; 2025 营养健康系统 版权所有</p>
        </div>
    </div>
</footer>

<script>
const chart = echarts.init(document.getElementById('chart'));
const nutrientPieChart = echarts.init(document.getElementById('nutrientPieChart'));
let nodeTooltip = document.getElementById('nodeTooltip');
let currentGraphData = null;
let searchHistory = [];
let hotSearches = [];

// 页面加载时获取所有节点数据
window.addEventListener('DOMContentLoaded', function() {
    // 显示加载动画
    document.getElementById('loadingOverlay').classList.remove('hidden');
    
    // 加载搜索历史
    loadSearchHistory();
    
    // 加载热门搜索
    loadHotSearches();
    
    // 初始化图表
    loadAllNodes();
    
    // 加载快捷查询列表
    loadQuickSearchList();
    
    // 绑定导出按钮事件
    document.getElementById('exportImageBtn').addEventListener('click', exportAsImage);
    document.getElementById('exportDataBtn').addEventListener('click', exportAsJson);
    
    // 绑定视图切换按钮事件
    document.getElementById('graphViewBtn').addEventListener('click', switchToGraphView);
    document.getElementById('listViewBtn').addEventListener('click', switchToListView);
    
    // 绑定搜索框事件
    document.getElementById('searchInput').addEventListener('keyup', function(e) {
        if (e.key === 'Enter') {
            search();
        } else {
            // 输入时进行模糊搜索
            const keyword = this.value.trim();
            if (keyword.length >= 1) {
                searchFoods(keyword);
            } else {
                document.getElementById('searchResults').classList.add('hidden');
            }
        }
    });
    
    // 绑定清除历史按钮事件
    document.getElementById('clearHistoryBtn').addEventListener('click', clearSearchHistory);
    
    // 窗口大小变化时重新调整图表大小
    window.addEventListener('resize', function() {
        chart.resize();
        nutrientPieChart.resize();
    });
});

// 加载快捷查询列表
function loadQuickSearchList() {
    // 从后端获取食物列表
    axios.get('http://localhost:8080/api/kg/search?keyword=')
        .then(response => {
            const foods = response.data;
            const quickSearchList = document.getElementById('quickSearchList');
            quickSearchList.innerHTML = '';
            
            // 只显示前10个食物
            const displayFoods = foods.slice(0, 10);
            
            // 生成不同的颜色
            const colors = ['bg-red-500', 'bg-yellow-500', 'bg-orange-500', 'bg-red-600',
                           'bg-blue-100', 'bg-yellow-200', 'bg-pink-300', 'bg-green-500',
                           'bg-orange-600', 'bg-indigo-500'];
            
            displayFoods.forEach((food, index) => {
                const colorClass = colors[index % colors.length];
                const item = document.createElement('div');
                item.className = 'sidebar-item p-2 rounded text-sm flex items-center';
                item.innerHTML = `<span class="w-2 h-2 rounded-full ${colorClass} mr-2"></span>${food.name}`;
                item.addEventListener('click', () => quickSearch(food.name));
                quickSearchList.appendChild(item);
            });
        })
        .catch(error => {
            console.error('获取食物列表失败:', error);
            // 使用默认数据
            const defaultFoods = ['苹果', '香蕉', '橙子', '西红柿', '牛奶', '鸡蛋', '三文鱼', '菠菜', '胡萝卜', '蓝莓'];
            const colors = ['bg-red-500', 'bg-yellow-500', 'bg-orange-500', 'bg-red-600',
                           'bg-blue-100', 'bg-yellow-200', 'bg-pink-300', 'bg-green-500',
                           'bg-orange-600', 'bg-indigo-500'];
            
            const quickSearchList = document.getElementById('quickSearchList');
            quickSearchList.innerHTML = '';
            
            defaultFoods.forEach((food, index) => {
                const colorClass = colors[index];
                const item = document.createElement('div');
                item.className = 'sidebar-item p-2 rounded text-sm flex items-center';
                item.innerHTML = `<span class="w-2 h-2 rounded-full ${colorClass} mr-2"></span>${food}`;
                item.addEventListener('click', () => quickSearch(food));
                quickSearchList.appendChild(item);
            });
        });
}

// 切换到图谱视图
function switchToGraphView() {
    document.getElementById('graphViewBtn').classList.remove('bg-gray-200', 'text-gray-700');
    document.getElementById('graphViewBtn').classList.add('bg-green-600', 'text-white');
    document.getElementById('listViewBtn').classList.remove('bg-green-600', 'text-white');
    document.getElementById('listViewBtn').classList.add('bg-gray-200', 'text-gray-700');
    document.getElementById('chart').classList.remove('hidden');
    document.getElementById('listView').classList.add('hidden');
    chart.resize();
}

// 切换到列表视图
function switchToListView() {
    document.getElementById('listViewBtn').classList.remove('bg-gray-200', 'text-gray-700');
    document.getElementById('listViewBtn').classList.add('bg-green-600', 'text-white');
    document.getElementById('graphViewBtn').classList.remove('bg-green-600', 'text-white');
    document.getElementById('graphViewBtn').classList.add('bg-gray-200', 'text-gray-700');
    document.getElementById('chart').classList.add('hidden');
    document.getElementById('listView').classList.remove('hidden');
    renderListView();
}

// 渲染列表视图
function renderListView() {
    if (!currentGraphData) return;
    
    const listView = document.getElementById('listView');
    listView.innerHTML = '';
    
    // 创建食品部分
    if (currentGraphData.foods && currentGraphData.foods.length > 0) {
        const foodSection = document.createElement('div');
        foodSection.className = 'mb-6';
        
        const foodTitle = document.createElement('h3');
        foodTitle.className = 'text-lg font-semibold mb-3 flex items-center';
        foodTitle.innerHTML = '<div class="w-3 h-3 rounded-full bg-orange-400 mr-2"></div>食品';
        foodSection.appendChild(foodTitle);
        
        const foodList = document.createElement('div');
        foodList.className = 'grid grid-cols-1 md:grid-cols-2 gap-3';
        
        currentGraphData.foods.forEach(food => {
            const foodItem = document.createElement('div');
            foodItem.className = 'p-3 bg-orange-50 rounded-lg';
            foodItem.innerHTML = `
                <div class="font-semibold text-orange-700">${food.name}</div>
                <div class="text-sm text-gray-600 mt-1">${food.description || '暂无描述'}</div>
            `;
            foodList.appendChild(foodItem);
        });
        
        foodSection.appendChild(foodList);
        listView.appendChild(foodSection);
    }
    
    // 创建营养素部分
    if (currentGraphData.nutrients && currentGraphData.nutrients.length > 0) {
        const nutrientSection = document.createElement('div');
        nutrientSection.className = 'mb-6';
        
        const nutrientTitle = document.createElement('h3');
        nutrientTitle.className = 'text-lg font-semibold mb-3 flex items-center';
        nutrientTitle.innerHTML = '<div class="w-3 h-3 rounded-full bg-blue-400 mr-2"></div>营养素';
        nutrientSection.appendChild(nutrientTitle);
        
        const nutrientList = document.createElement('div');
        nutrientList.className = 'grid grid-cols-1 md:grid-cols-2 gap-3';
        
        currentGraphData.nutrients.forEach(nutrient => {
            const nutrientItem = document.createElement('div');
            nutrientItem.className = 'p-3 bg-blue-50 rounded-lg';
            nutrientItem.innerHTML = `
                <div class="font-semibold text-blue-700">${nutrient.name}</div>
                <div class="text-sm text-gray-600 mt-1">${nutrient.description || '暂无描述'}</div>
            `;
            nutrientList.appendChild(nutrientItem);
        });
        
        nutrientSection.appendChild(nutrientList);
        listView.appendChild(nutrientSection);
    }
    
    // 创建功效部分
    if (currentGraphData.benefits && currentGraphData.benefits.length > 0) {
        const benefitSection = document.createElement('div');
        benefitSection.className = 'mb-6';
        
        const benefitTitle = document.createElement('h3');
        benefitTitle.className = 'text-lg font-semibold mb-3 flex items-center';
        benefitTitle.innerHTML = '<div class="w-3 h-3 rounded-full bg-green-400 mr-2"></div>功效';
        benefitSection.appendChild(benefitTitle);
        
        const benefitList = document.createElement('div');
        benefitList.className = 'grid grid-cols-1 md:grid-cols-2 gap-3';
        
        currentGraphData.benefits.forEach(benefit => {
            const benefitItem = document.createElement('div');
            benefitItem.className = 'p-3 bg-green-50 rounded-lg';
            benefitItem.innerHTML = `
                <div class="font-semibold text-green-700">${benefit.name}</div>
                <div class="text-sm text-gray-600 mt-1">${benefit.description || '暂无描述'}</div>
            `;
            benefitList.appendChild(benefitItem);
        });
        
        benefitSection.appendChild(benefitList);
        listView.appendChild(benefitSection);
    }
}

// 导出为图片
function exportAsImage() {
    // 使用html2canvas将图表转换为图片
    html2canvas(document.querySelector('.chart-container')).then(canvas => {
        // 将canvas转换为blob
        canvas.toBlob(function(blob) {
            // 使用FileSaver.js保存文件
            saveAs(blob, `食品营养知识图谱_${new Date().toISOString().slice(0,10)}.png`);
        });
    });
    
    // 显示成功提示
    Swal.fire({
        title: '导出成功',
        text: '图谱已成功导出为PNG图片',
        icon: 'success',
        timer: 2000,
        showConfirmButton: false
    });
}

// 导出为JSON
function exportAsJson() {
    if (!currentGraphData) return;
    
    // 创建Blob对象
    const blob = new Blob([JSON.stringify(currentGraphData, null, 2)], {type: 'application/json'});
    
    // 使用FileSaver.js保存文件
    saveAs(blob, `食品营养知识图谱数据_${new Date().toISOString().slice(0,10)}.json`);
    
    // 显示成功提示
    Swal.fire({
        title: '导出成功',
        text: '图谱数据已成功导出为JSON文件',
        icon: 'success',
        timer: 2000,
        showConfirmButton: false
    });
}

// 加载搜索历史
function loadSearchHistory() {
    const savedHistory = localStorage.getItem('searchHistory');
    if (savedHistory) {
        searchHistory = JSON.parse(savedHistory);
        updateSearchHistoryUI();
    }
}

// 更新搜索历史UI
function updateSearchHistoryUI() {
    const historyContainer = document.getElementById('searchHistory');
    historyContainer.innerHTML = '';
    
    // 只显示最近5条记录
    const recentHistory = searchHistory.slice(0, 5);
    
    if (recentHistory.length === 0) {
        const emptyItem = document.createElement('div');
        emptyItem.className = 'text-sm text-gray-500 italic';
        emptyItem.textContent = '暂无搜索历史';
        historyContainer.appendChild(emptyItem);
        return;
    }
    
    recentHistory.forEach(item => {
        const historyItem = document.createElement('div');
        historyItem.className = 'search-history-item cursor-pointer';
        historyItem.innerHTML = `
            <i class="fas fa-history text-gray-400 mr-2"></i>
            <span>${item}</span>
        `;
        historyItem.addEventListener('click', () => {
            document.getElementById('searchInput').value = item;
            search();
        });
        historyContainer.appendChild(historyItem);
    });
}

// 添加搜索历史
function addSearchHistory(keyword) {
    // 如果已存在，先移除
    const index = searchHistory.indexOf(keyword);
    if (index !== -1) {
        searchHistory.splice(index, 1);
    }
    
    // 添加到开头
    searchHistory.unshift(keyword);
    
    // 限制最多保存10条
    if (searchHistory.length > 10) {
        searchHistory.pop();
    }
    
    // 保存到localStorage
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory));
    
    // 更新UI
    updateSearchHistoryUI();
    
    // 更新热门搜索
    updateHotSearches(keyword);
}

// 清除搜索历史
function clearSearchHistory() {
    searchHistory = [];
    localStorage.removeItem('searchHistory');
    updateSearchHistoryUI();
    
    Swal.fire({
        title: '已清除',
        text: '搜索历史已清除',
        icon: 'success',
        timer: 1500,
        showConfirmButton: false
    });
}

// 加载热门搜索
function loadHotSearches() {
    const savedHotSearches = localStorage.getItem('hotSearches');
    if (savedHotSearches) {
        hotSearches = JSON.parse(savedHotSearches);
    } else {
        // 默认热门搜索
        hotSearches = [
            {keyword: '苹果', count: 5},
            {keyword: '香蕉', count: 4},
            {keyword: '西红柿', count: 3},
            {keyword: '维生素C', count: 2},
            {keyword: '增强免疫力', count: 1}
        ];
        localStorage.setItem('hotSearches', JSON.stringify(hotSearches));
    }
    updateHotSearchesUI();
}

// 更新热门搜索UI
function updateHotSearchesUI() {
    const container = document.getElementById('hotSearchTags');
    container.innerHTML = '';
    
    // 按搜索次数排序
    hotSearches.sort((a, b) => b.count - a.count);
    
    // 只显示前5个
    const topSearches = hotSearches.slice(0, 5);
    
    topSearches.forEach(item => {
        const tag = document.createElement('span');
        
        // 根据关键词类型设置不同的样式
        let tagClass = 'tag tag-food';
        if (item.keyword.includes('维生素') || item.keyword.includes('蛋白质') || item.keyword.includes('矿物质')) {
            tagClass = 'tag tag-nutrient';
        } else if (item.keyword.includes('增强') || item.keyword.includes('促进') || item.keyword.includes('预防')) {
            tagClass = 'tag tag-benefit';
        }
        
        tag.className = `${tagClass} cursor-pointer`;
        tag.textContent = item.keyword;
        tag.addEventListener('click', () => quickSearch(item.keyword));
        container.appendChild(tag);
    });
}

// 更新热门搜索
function updateHotSearches(keyword) {
    // 查找是否已存在
    const existingIndex = hotSearches.findIndex(item => item.keyword === keyword);
    
    if (existingIndex !== -1) {
        // 已存在，增加计数
        hotSearches[existingIndex].count++;
    } else {
        // 不存在，添加新项
        hotSearches.push({keyword: keyword, count: 1});
    }
    
    // 限制最多保存20条
    if (hotSearches.length > 20) {
        // 按计数排序，移除最少的
        hotSearches.sort((a, b) => a.count - b.count);
        hotSearches.shift();
    }
    
    // 保存到localStorage
    localStorage.setItem('hotSearches', JSON.stringify(hotSearches));
    
    // 更新UI
    updateHotSearchesUI();
}

// 快捷搜索
function quickSearch(keyword) {
    document.getElementById('searchInput').value = keyword;
    search();
}

// 模糊搜索食物
function searchFoods(keyword) {
    if (!keyword) return;
    
    axios.get(`http://localhost:8080/api/kg/search?keyword=${encodeURIComponent(keyword)}`)
        .then(response => {
            const foods = response.data;
            displaySearchResults(foods);
        })
        .catch(error => {
            console.error('搜索食物失败:', error);
            // 使用模拟数据
            const mockFoods = [
                {id: 1, name: '苹果', type: 'FOOD'},
                {id: 2, name: '香蕉', type: 'FOOD'},
                {id: 3, name: '西红柿', type: 'FOOD'}
            ].filter(food => food.name.includes(keyword));
            
            displaySearchResults(mockFoods);
        });
}

// 显示搜索结果
function displaySearchResults(foods) {
    const resultsContainer = document.getElementById('searchResults');
    
    if (foods.length === 0) {
        resultsContainer.innerHTML = '<div class="p-2 text-sm text-gray-500">未找到相关食物</div>';
        resultsContainer.classList.remove('hidden');
        return;
    }
    
    resultsContainer.innerHTML = '';
    
    foods.forEach(food => {
        const item = document.createElement('div');
        item.className = 'p-2 hover:bg-gray-100 cursor-pointer text-sm';
        item.textContent = food.name;
        item.addEventListener('click', () => {
            document.getElementById('searchInput').value = food.name;
            search();
            resultsContainer.classList.add('hidden');
        });
        resultsContainer.appendChild(item);
    });
    
    resultsContainer.classList.remove('hidden');
}

// 模拟所有节点数据
const mockAllNodesData = {
    "foods": [
        {"id": 1, "name": "苹果", "type": "FOOD", "description": "苹果富含维生素C和膳食纤维，是一种常见的水果。"},
        {"id": 2, "name": "香蕉", "type": "FOOD", "description": "香蕉富含钾和维生素B6，是一种营养丰富的水果。"},
        {"id": 3, "name": "橙子", "type": "FOOD", "description": "橙子富含维生素C，是一种酸甜可口的水果。"}
    ],
    "nutrients": [
        {"id": 4, "name": "维生素C", "type": "NUTRIENT", "description": "维生素C是一种重要的抗氧化剂，有助于增强免疫系统。"},
        {"id": 5, "name": "膳食纤维", "type": "NUTRIENT", "description": "膳食纤维有助于消化系统健康，可以预防便秘。"},
        {"id": 6, "name": "钾", "type": "NUTRIENT", "description": "钾是一种重要的电解质，有助于维持正常的血压水平。"},
        {"id": 7, "name": "维生素B6", "type": "NUTRIENT", "description": "维生素B6有助于蛋白质代谢和红细胞生成。"}
    ],
    "benefits": [
        {"id": 8, "name": "增强免疫力", "type": "BENEFIT", "description": "增强身体抵抗疾病的能力。"},
        {"id": 9, "name": "促进消化", "type": "BENEFIT", "description": "帮助食物在消化系统中更好地分解和吸收。"},
        {"id": 10, "name": "降低胆固醇", "type": "BENEFIT", "description": "减少血液中的胆固醇水平，有助于心脏健康。"},
        {"id": 11, "name": "降低血压", "type": "BENEFIT", "description": "帮助维持健康的血压水平。"},
        {"id": 12, "name": "增强能量", "type": "BENEFIT", "description": "提供身体所需的能量。"}
    ],
    "relations": [
        {"source": "苹果", "target": "维生素C", "type": "CONTAINS"},
        {"source": "苹果", "target": "膳食纤维", "type": "CONTAINS"},
        {"source": "苹果", "target": "增强免疫力", "type": "HAS_BENEFIT"},
        {"source": "苹果", "target": "促进消化", "type": "HAS_BENEFIT"},
        {"source": "苹果", "target": "降低胆固醇", "type": "HAS_BENEFIT"},
        {"source": "香蕉", "target": "钾", "type": "CONTAINS"},
        {"source": "香蕉", "target": "维生素B6", "type": "CONTAINS"},
        {"source": "香蕉", "target": "膳食纤维", "type": "CONTAINS"},
        {"source": "香蕉", "target": "降低血压", "type": "HAS_BENEFIT"},
        {"source": "香蕉", "target": "增强能量", "type": "HAS_BENEFIT"},
        {"source": "香蕉", "target": "促进消化", "type": "HAS_BENEFIT"},
        {"source": "橙子", "target": "维生素C", "type": "CONTAINS"},
        {"source": "橙子", "target": "增强免疫力", "type": "HAS_BENEFIT"}
    ]
};

// 单个食品的模拟数据
const mockData = {
    "苹果": {
        "food": "苹果",
        "description": "苹果富含维生素C和膳食纤维，是一种常见的水果。",
        "nutrients": [
            {"name": "维生素C", "description": "维生素C是一种重要的抗氧化剂，有助于增强免疫系统。"},
            {"name": "膳食纤维", "description": "膳食纤维有助于消化系统健康，可以预防便秘。"},
            {"name": "钾", "description": "钾是一种重要的电解质，有助于维持正常的血压水平。"}
        ],
        "benefits": [
            {"name": "增强免疫力", "description": "苹果中的抗氧化物质可以帮助增强免疫系统。"},
            {"name": "促进消化", "description": "苹果中的膳食纤维有助于促进消化系统健康。"},
            {"name": "降低胆固醇", "description": "苹果中的果胶可以帮助降低血液中的胆固醇水平。"}
        ]
    },
    "香蕉": {
        "food": "香蕉",
        "description": "香蕉富含钾和维生素B6，是一种营养丰富的水果。",
        "nutrients": [
            {"name": "钾", "description": "钾是一种重要的电解质，有助于维持正常的血压水平。"},
            {"name": "维生素B6", "description": "维生素B6有助于蛋白质代谢和红细胞生成。"},
            {"name": "膳食纤维", "description": "膳食纤维有助于消化系统健康，可以预防便秘。"}
        ],
        "benefits": [
            {"name": "降低血压", "description": "香蕉中的钾有助于降低血压。"},
            {"name": "增强能量", "description": "香蕉中的碳水化合物是快速能量的良好来源。"},
            {"name": "改善消化", "description": "香蕉中的膳食纤维有助于促进消化系统健康。"}
        ]
    }
};

// 加载所有节点
function loadAllNodes() {
    // 显示加载动画
    document.getElementById('loadingOverlay').classList.remove('hidden');
    
    // 尝试从后端获取所有节点数据
    axios.get('http://localhost:8080/api/kg/all')
        .then(response => {
            const data = response.data;
            renderFullGraph(data);
        })
        .catch(() => {
            // 如果后端请求失败，使用模拟数据
            setTimeout(() => {
                renderFullGraph(mockAllNodesData);
            }, 800); // 添加延迟以展示加载动画效果
        });
}

// 更新统计信息和营养成分分布图
function updateStatistics(data) {
    // 更新统计数量
    const foodCount = data.foods ? data.foods.length : 0;
    const nutrientCount = data.nutrients ? data.nutrients.length : 0;
    const benefitCount = data.benefits ? data.benefits.length : 0;
    
    document.getElementById('foodCount').textContent = foodCount;
    document.getElementById('nutrientCount').textContent = nutrientCount;
    document.getElementById('benefitCount').textContent = benefitCount;
    
    // 更新营养成分分布饼图
    if (data.nutrients && Array.isArray(data.nutrients) && data.nutrients.length > 0) {
        // 按类型分组营养素
        const nutrientTypes = {};
        data.nutrients.forEach(nutrient => {
            // 简单分类营养素
            let type = '其他';
            if (nutrient.name.includes('维生素')) type = '维生素';
            else if (nutrient.name.includes('钙') || nutrient.name.includes('铁') ||
                     nutrient.name.includes('钾') || nutrient.name.includes('钠') ||
                     nutrient.name.includes('锌') || nutrient.name.includes('镁')) {
                type = '矿物质';
            }
            else if (nutrient.name.includes('蛋白质')) type = '蛋白质';
            else if (nutrient.name.includes('脂肪')) type = '脂肪';
            else if (nutrient.name.includes('碳水') || nutrient.name.includes('纤维')) type = '碳水化合物';
            
            if (!nutrientTypes[type]) nutrientTypes[type] = 0;
            nutrientTypes[type]++;
        });
        
        // 转换为饼图数据
        const pieData = Object.keys(nutrientTypes).map(type => {
            return {
                name: type,
                value: nutrientTypes[type]
            };
        });
        
        // 设置饼图配置
        const pieOption = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 10,
                data: Object.keys(nutrientTypes)
            },
            series: [
                {
                    name: '营养成分',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '12',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: pieData
                }
            ]
        };
        
        // 渲染饼图
        nutrientPieChart.setOption(pieOption);
    } else {
        // 如果没有营养素数据，显示空饼图
        nutrientPieChart.setOption({
            title: {
                text: '暂无营养成分数据',
                left: 'center',
                top: 'middle',
                textStyle: {
                    color: '#999',
                    fontSize: 14
                }
            },
            series: [
                {
                    type: 'pie',
                    radius: ['40%', '70%'],
                    data: []
                }
            ]
        });
    }
}

// 渲染完整图谱
function renderFullGraph(data) {
    // 保存当前图谱数据，供列表视图使用
    currentGraphData = data;
    
    // 更新统计信息和营养成分分布图
    updateStatistics(data);
    // 清空图表
    chart.clear();
    console.log("接收到的数据:", data); // 调试用
    
    const nodes = [], links = [];
    const categories = [
        {name: '食品', itemStyle: {color: '#F59E0B'}},
        {name: '营养素', itemStyle: {color: '#3B82F6'}},
        {name: '功效', itemStyle: {color: '#10B981'}}
    ];
    
    // 添加食品节点
    if (data.foods && Array.isArray(data.foods)) {
        data.foods.forEach(food => {
            nodes.push({
                id: food.id,
                name: food.name,
                category: 0, // 食品类别索引
                symbolSize: 50,
                value: food.description,
                itemStyle: {
                    color: '#F59E0B'
                }
            });
        });
    }
    
    // 添加营养素节点
    if (data.nutrients && Array.isArray(data.nutrients)) {
        data.nutrients.forEach(nutrient => {
            nodes.push({
                id: nutrient.id,
                name: nutrient.name,
                category: 1, // 营养素类别索引
                symbolSize: 40,
                value: nutrient.description,
                itemStyle: {
                    color: '#3B82F6'
                }
            });
        });
    }
    
    // 添加功效节点
    if (data.benefits && Array.isArray(data.benefits)) {
        data.benefits.forEach(benefit => {
            nodes.push({
                id: benefit.id,
                name: benefit.name,
                category: 2, // 功效类别索引
                symbolSize: 40,
                value: benefit.description,
                itemStyle: {
                    color: '#10B981'
                }
            });
        });
    }
    
    // 添加关系
    // 使用后端返回的关系数据
    if (data.relations && Array.isArray(data.relations) && data.relations.length > 0) {
        console.log("使用后端返回的关系数据:", data.relations);
        
        // 创建节点名称到节点索引的映射
        const nodeNameToIndex = {};
        nodes.forEach((node, index) => {
            nodeNameToIndex[node.name] = index;
        });
        
        console.log("节点名称到索引映射:", nodeNameToIndex);
        
        data.relations.forEach(relation => {
            // 确保源节点和目标节点都存在
            if (relation.source && relation.target) {
                const sourceIndex = nodeNameToIndex[relation.source];
                const targetIndex = nodeNameToIndex[relation.target];
                
                if (sourceIndex !== undefined && targetIndex !== undefined) {
                    const linkStyle = {};
                    
                    // 根据关系类型设置不同的样式
                    if (relation.type === "CONTAINS") {
                        linkStyle.color = '#3B82F6';
                    } else if (relation.type === "HAS_BENEFIT") {
                        linkStyle.color = '#10B981';
                    } else {
                        linkStyle.color = '#999';
                    }
                    
                    links.push({
                        source: sourceIndex,
                        target: targetIndex,
                        lineStyle: {
                            ...linkStyle,
                            width: 2
                        }
                    });
                } else {
                    console.warn(`找不到节点: 源=${relation.source}, 目标=${relation.target}`);
                }
            }
        });
    } else {
        console.log("后端未返回关系数据或关系数据为空，使用随机生成的关系");
        
        // 创建节点名称到节点索引的映射
        const nodeNameToIndex = {};
        nodes.forEach((node, index) => {
            nodeNameToIndex[node.name] = index;
        });
        
        // 如果后端没有返回关系数据，则生成随机关系
        if (data.foods && Array.isArray(data.foods) && data.foods.length > 0) {
            // 为每个食品生成与营养素的关系
            if (data.nutrients && Array.isArray(data.nutrients) && data.nutrients.length > 0) {
                data.foods.forEach(food => {
                    // 为每个食品随机选择3-5个营养素
                    const selectedNutrients = [];
                    const nutrientCount = Math.min(data.nutrients.length, Math.floor(Math.random() * 3) + 3);
                    
                    for (let i = 0; i < nutrientCount; i++) {
                        let nutrient;
                        do {
                            nutrient = data.nutrients[Math.floor(Math.random() * data.nutrients.length)];
                        } while (selectedNutrients.includes(nutrient.id));
                        
                        selectedNutrients.push(nutrient.id);
                        
                        const sourceIndex = nodeNameToIndex[food.name];
                        const targetIndex = nodeNameToIndex[nutrient.name];
                        
                        if (sourceIndex !== undefined && targetIndex !== undefined) {
                            links.push({
                                source: sourceIndex,
                                target: targetIndex,
                                lineStyle: {
                                    color: '#3B82F6',
                                    width: 2
                                }
                            });
                        }
                    }
                });
            }
            
            // 为每个食品生成与功效的关系
            if (data.benefits && Array.isArray(data.benefits) && data.benefits.length > 0) {
                data.foods.forEach(food => {
                    // 为每个食品随机选择2-4个功效
                    const selectedBenefits = [];
                    const benefitCount = Math.min(data.benefits.length, Math.floor(Math.random() * 3) + 2);
                    
                    for (let i = 0; i < benefitCount; i++) {
                        let benefit;
                        do {
                            benefit = data.benefits[Math.floor(Math.random() * data.benefits.length)];
                        } while (selectedBenefits.includes(benefit.id));
                        
                        selectedBenefits.push(benefit.id);
                        
                        const sourceIndex = nodeNameToIndex[food.name];
                        const targetIndex = nodeNameToIndex[benefit.name];
                        
                        if (sourceIndex !== undefined && targetIndex !== undefined) {
                            links.push({
                                source: sourceIndex,
                                target: targetIndex,
                                lineStyle: {
                                    color: '#10B981',
                                    width: 2
                                }
                            });
                        }
                    }
                });
            }
        }
    }
    
    console.log("生成的节点数:", nodes.length);
    console.log("生成的关系数:", links.length);
    
    // ECharts配置
    const option = {
        title: {
            text: '食品营养知识图谱',
            subtext: '全局视图',
            top: 'top',
            left: 'center'
        },
        tooltip: {
            formatter: function(params) {
                if (params.dataType === 'node') {
                    return `<div style="font-weight:bold;margin-bottom:5px;">${params.name}</div>${params.value || ''}`;
                }
                return '';
            }
        },
        legend: [{
            data: categories.map(a => a.name),
            selected: {
                '食品': true,
                '营养素': true,
                '功效': true
            }
        }],
        animationDuration: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [{
            name: '知识图谱',
            type: 'graph',
            layout: 'force',
            data: nodes,
            links: links,
            categories: categories,
            roam: true, // 允许缩放和平移
            zoom: 1,
            label: {
                show: true,
                position: 'right',
                formatter: '{b}'
            },
            force: {
                repulsion: 200,
                edgeLength: 120
            },
            lineStyle: {
                color: 'source',
                curveness: 0.3
            },
            emphasis: {
                focus: 'adjacency',
                lineStyle: {
                    width: 4
                }
            }
        }]
    };
    
    chart.setOption(option);
    
    // 隐藏加载动画
    document.getElementById('loadingOverlay').classList.add('hidden');
    
    // 绑定节点点击事件
    chart.off('click');
    chart.on('click', function(params) {
        if (params.dataType === 'node') {
            Swal.fire({
                title: params.name,
                html: `<p>${params.value || '暂无详细描述'}</p>`,
                icon: 'info'
            });
        }
    });
}

// 执行搜索
function search() {
    console.log("执行搜索...");
    const keyword = document.getElementById('searchInput').value.trim();
    if (!keyword) {
        Swal.fire('提示', '请输入食品名称', 'warning');
        return;
    }
    
    // 隐藏搜索结果
    document.getElementById('searchResults').classList.add('hidden');
    
    // 显示加载动画
    document.getElementById('loadingOverlay').classList.remove('hidden');

    // 添加到搜索历史
    addSearchHistory(keyword);
    
    // 直接从后端获取数据
    axios.get(`http://localhost:8080/api/kg/food?name=${encodeURIComponent(keyword)}`)
        .then(response => {
            console.log("搜索结果:", response.data);
            const data = response.data;
            if (data) {
                renderGraph(data);
                
                // 更新图表标题
                document.getElementById('graphTitle').textContent = `食品营养知识图谱 - ${keyword}`;
            } else {
                // 如果后端没有数据，尝试使用模拟数据
                if (mockData[keyword]) {
                    console.log("使用模拟数据:", keyword);
                    renderGraph(mockData[keyword]);
                    
                    // 更新图表标题
                    document.getElementById('graphTitle').textContent = `食品营养知识图谱 - ${keyword}`;
                } else {
                    document.getElementById('loadingOverlay').classList.add('hidden');
                    Swal.fire('提示', '未找到该食品的数据', 'warning');
                }
            }
        })
        .catch(error => {
            console.error("搜索错误:", error);
            
            // 如果API请求失败，尝试使用模拟数据
            if (mockData[keyword]) {
                console.log("API请求失败，使用模拟数据:", keyword);
                renderGraph(mockData[keyword]);
                
                // 更新图表标题
                document.getElementById('graphTitle').textContent = `食品营养知识图谱 - ${keyword}`;
            } else {
                document.getElementById('loadingOverlay').classList.add('hidden');
                Swal.fire('错误', '搜索过程中发生错误', 'error');
                // 确保隐藏加载动画
                document.getElementById('loadingOverlay').classList.add('hidden');
            }
        });
}

// 渲染图谱
function renderGraph(data) {
    // 保存当前图谱数据，供列表视图使用
    currentGraphData = {
        foods: [{ name: data.food, description: data.description }],
        nutrients: data.nutrients || [],
        benefits: data.benefits || []
    };
    
    // 更新统计信息和营养成分分布图
    updateStatistics(currentGraphData);
    // 清空图表
    chart.clear();
    console.log("渲染图谱数据:", data);
    const nodes = [], links = [];
    const categories = [
        {name: '食品', itemStyle: {color: '#F59E0B'}},
        {name: '营养素', itemStyle: {color: '#3B82F6'}},
        {name: '功效', itemStyle: {color: '#10B981'}}
    ];

    // 主节点（食品）
    nodes.push({
        name: data.food,
        category: 0,
        symbolSize: 70,
        itemStyle: {color: '#F59E0B'},
        value: data.description
    });

    // 营养素节点
    if (data.nutrients && Array.isArray(data.nutrients)) {
        data.nutrients.forEach(n => {
            nodes.push({
                name: n.name,
                category: 1,
                symbolSize: 50,
                itemStyle: {color: '#3B82F6'},
                value: n.description
            });
        });
    }

    // 功效节点
    if (data.benefits && Array.isArray(data.benefits)) {
        data.benefits.forEach(b => {
            nodes.push({
                name: b.name,
                category: 2,
                symbolSize: 50,
                itemStyle: {color: '#10B981'},
                value: b.description
            });
        });
    }
    
    // 创建节点名称到节点索引的映射
    const nodeNameToIndex = {};
    nodes.forEach((node, index) => {
        nodeNameToIndex[node.name] = index;
    });
    
    // 添加关系连线
    if (data.nutrients && Array.isArray(data.nutrients)) {
        data.nutrients.forEach(n => {
            const sourceIndex = 0; // 食品节点总是第一个
            const targetIndex = nodeNameToIndex[n.name];
            if (targetIndex !== undefined) {
                links.push({
                    source: sourceIndex,
                    target: targetIndex,
                    lineStyle: {
                        color: '#3B82F6',
                        width: 2
                    }
                });
            }
        });
    }
    
    if (data.benefits && Array.isArray(data.benefits)) {
        data.benefits.forEach(b => {
            const sourceIndex = 0; // 食品节点总是第一个
            const targetIndex = nodeNameToIndex[b.name];
            if (targetIndex !== undefined) {
                links.push({
                    source: sourceIndex,
                    target: targetIndex,
                    lineStyle: {
                        color: '#10B981',
                        width: 2
                    }
                });
            }
        });
    }

    // ECharts配置
    const option = {
        title: {
            text: `食品营养知识图谱 - ${data.food}`,
            subtext: '搜索结果',
            top: 'top',
            left: 'center'
        },
        tooltip: {
            formatter: function(params) {
                if (params.dataType === 'node') {
                    return `<div style="font-weight:bold;margin-bottom:5px;">${params.name}</div>${params.value || ''}`;
                }
                return '';
            }
        },
        legend: [{
            data: categories.map(a => a.name),
            selected: {
                '食品': true,
                '营养素': true,
                '功效': true
            }
        }],
        animationDuration: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [{
            type: 'graph',
            layout: 'force',
            roam: true, // 允许缩放和平移
            zoom: 1.5, // 初始缩放比例
            label: {
                show: true,
                position: 'right',
                formatter: '{b}'
            },
            draggable: true,
            emphasis: {
                scale: true,
                focus: 'adjacency',
                lineStyle: { width: 4 }
            },
            force: { repulsion: 800 },
            data: nodes,
            links: links,
            categories: categories
        }]
    };

    chart.setOption(option);

    // 隐藏加载动画
    document.getElementById('loadingOverlay').classList.add('hidden');

    // 绑定节点点击事件
    chart.off('click'); // 避免多次绑定
    chart.on('click', function(params) {
        if (params.dataType === 'node') {
            Swal.fire({
                title: params.name,
                html: `<p>${params.value || '暂无详细描述'}</p>`,
                icon: 'info'
            });
        }
    });
}
</script>
<!-- 添加auth.js以处理登录状态 -->
<script src="../js/auth.js"></script>
</body>
</html>